using System;
using DG.Tweening;
using LitJson;
using UnityEngine;

namespace CGF
{
    public partial class PanelLeasePay : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        private JsonData data;
        private int currDeviceType;
        private float priceVIP;
        private Action onPaySuccess;

        public static void Open(JsonData data, Action onPaySuccess)
        {
            var instance = UIManagerComponent.instance.OpenUI<PanelLeasePay>(UILayer.Normal, RootComponent.instance, true);
            instance.onPaySuccess = onPaySuccess;
            instance.SetProsBindCompletedAction(() =>
            {
                instance.SetInfo(data);
            });
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelLeasePay>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelLeasePay", layer, isFloat);
            BindProperties(transform);

            BtnClose.SetClick(Close);

            Vector2 pos = Dialog.rectTransform.anchoredPosition;
            pos.y = -900;
            Dialog.rectTransform.anchoredPosition = pos;
            Dialog.rectTransform.DOAnchorPosY(20, 0.2f).OnComplete(() =>
            {
                Dialog.rectTransform.DOAnchorPosY(0, 0.1f);
            });

            BtnPay.SetClick(async () =>
            {
                if (!SwitchButton.isOn)
                {
                    CGF.Dialog.Alert(I18N_must_agree);
                    return;
                }
                if ((int)UserInfo.Info["level"] < (int)data["buy_level"])
                {
                    CGF.Dialog.Alert(CommAssets.instance.I18N_level_not_enough);
                    return;
                }
                if (UserInfo.balance < priceVIP)
                {
                    CGF.Dialog.Confirm(I18N_balance_not_enough, () =>
                    {
                        PanelRecharge.Open();
                    }, null, I18N_goto_rechage);
                    return;
                }
                JsonData postData = new JsonData();
                postData["num"] = data.Contains("num") ? (int)data["num"] : 1;
                postData["shop_id"] = (int)data["id"];
                var res = await Network.Post("/v1/order/buy", postData);
                if (res.success)
                {
                    if (currDeviceType == 1)
                    {
                        UserInfo.HaveBoughtExpDevice = true;
                        RootComponent.instance.GetComponent<PanelLeaseDevices>()?.RemoveExpDevices();
                    }
                    UserInfo.IsLoggedIn().Invoke();
                    Close();
                    CGF.Dialog.Alert(I18N_lease_success, () =>
                    {
                        onPaySuccess?.Invoke();
                    });
                }
            });

            TextPrivacy.SetClick(() =>
            {
                PanelPrivacy.Open();
            });
            
            ReqData();
            gameObject.AddEnableEvent(ReqData);
        }

        private void SetInfo(JsonData data)
        {
            this.data = data;
            currDeviceType = Mathf.Max(1, (int)data["type"]);
            Device.GetComponent<Device>().SetInfo(currDeviceType, (int)data["period"], false);
            int num = data.Contains("num") ? (int)data["num"] : 1;
            TextTitle2.text = $"{Utils.GetI18N(data["name"].ToString())}  <b>x{num}</b>";
            float priceDefault = (int)data["price"] * num;
            priceVIP = priceDefault * UserInfo.discount;
            PriceVIP.text = $"{CommAssets.instance.I18N_price_vip}: {I18N.Currency} {StringHelper.Format2Decimal(priceVIP * 0.01f)}";
            PriceDefault.text = $"{CommAssets.instance.I18N_price_default}: {I18N.Currency} {StringHelper.Format2Decimal(priceDefault * 0.01f)}";
        }

        private async void ReqData()
        {
            gameObject.GetComponent<Canvas>().sortingOrder = 1000;
            var res = await Network.Get("/v1/user/wallet");
            JsonData wallet = res.jsonData["data"]["wallet"];
            UserInfo.balance = (int)wallet["balance"];
            Balance.text = $"{CommAssets.instance.I18N_wallet_balance} {I18N.Currency} {StringHelper.Format2Decimal(UserInfo.balance * 0.01f)}";
            EventManager.Emit(new Event_UserInfoUpdate());
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

    }
}
